package log_stash

import (
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"time"
)

type Log struct {
	ip     string `json:"ip"`
	userID uint   `json:"user_id"`
	addr   string `json:"addr"`
}

func New(ip string, token string) *Log {
	// 解析token
	claims, err := utils.ParseToken(token)
	var userID uint
	if err == nil {
		userID = claims.UserID
	}

	// 拿到用户id
	return &Log{
		ip:     ip,
		userID: userID,
		addr:   "内网",
	}
}

func NewLogByGin(c *gin.Context) *Log {
	ip := c.ClientIP()
	token := c.Request.Header.Get("token")
	return New(ip, token)
}

func (l Log) Debug(content string) {
	l.Send(DebugLevel, content)
}
func (l Log) Info(content string) {
	l.Send(InfoLevel, content)
}
func (l Log) Waring(content string) {
	l.Send(WaringLevel, content)
}
func (l Log) Errorf(content string) {
	l.Send(ErrorLevel, content)
}

// Send 入库
func (l Log) Send(level Level, content string) {
	err := common.DB.Create(&LogStashModel{
		IP:        l.ip,
		Addr:      l.addr,
		Level:     level,
		Content:   content,
		UserID:    l.userID,
		CreatedAt: time.Time{},
	}).Error
	if err != nil {
		logrus.Error(err.Error())
		return
	}
	fmt.Println(l.ip, l.userID, l.addr, content, level)
}

// Debug 调用 log_stash 访问以下函数进行入库操作
//func Debug(ip string, content string) {
//	std.Debug(ip, content)
//}
//
//// Info logs a message at level Debug on the standard logger.
//func Info(ip string, content string) {
//	std.Info(ip, content)
//}
//
//// Waring logs a message at level Debug on the standard logger.
//func Waring(ip string, content string) {
//	std.Waring(ip, content)
//}
//
//// Errorf logs a message at level Debug on the standard logger.
//func Errorf(ip string, content string) {
//	std.Errorf(ip, content)
//}
